'use strict';
const Controller = require('egg').Controller;
class ShoppingCartController extends Controller {
  /**
     * @api {Post} /api/shoppingCart 添加购物车
     * @apiGroup 购物车
     * @apiParam {String}  goods_id    商品id  (必填)
     * @apiParam {int}  num         商品数量  (必填)
     * @apiParamExample 参数模板
     {
        goods_id: 1,
        num: 2
      }
     * @apiSuccessExample 成功返回
     * {
     *    "msg":'加入购物车'
     * }
     *
     * @apiErrorExample 错误返回
     * {
     *  "msg":"添加失败"
     * }
     *
     */

  async create() {
    const { ctx } = this;
    const { ShoppingCart } = this.app.model.Tables.Shop;
    const dataObj = ctx.request.body;

    try {
      if (new ctx.helper.checkData(this, 'goods_id').checkDataRes) {
        dataObj.user_id = ctx.userInfo.id;
        // 查找或创建
        const curData = await ShoppingCart.findCreateFind({
          where: {
            user_id: dataObj.user_id,
            goods_id: dataObj.goods_id,
            project_id:
              ctx.userInfo.project_id ||
              (ctx.adminInfo && ctx.adminInfo.project_id) ||
              ctx.request.body.project_id,
          },
          defaults: {
            num: dataObj.num || 1,
          },
        });

        if (curData[1]) {
          ctx.body = this.ctx.response.success('成功加入购物车');
        } else {
          // 检测数量的变化，商品一致就只需要在原来的购物车上增加数量即可
          let num = curData[0].num + dataObj.num;

          await ShoppingCart.update(
            { num },
            {
              where: {
                goods_id: dataObj.goods_id,
                user_id: dataObj.user_id,
                project_id:
                  ctx.userInfo.project_id ||
                  (ctx.adminInfo && ctx.adminInfo.project_id) ||
                  ctx.request.body.project_id,
              },
              fields: {
                num,
              },
            }
          );
          ctx.body = this.ctx.response.success('商品已在购物车中，数量已更新');
        }
      }
    } catch (error) {
      console.log(error);
      ctx.body = ctx.response.error(error.message);
    }
  }
  // 获取自己的购物车信息
  /**
     * @api {Get} /api/shoppingCart 获取自己的购物车信息
     * @apiGroup 购物车
     * @apiParam {int}  project_id     项目id  (必填)
     * @apiParamExample 参数模板
     {
       project_id: 3
     }
     * @apiSuccessExample  成功返回
     {
        "msg": "成功操作",
    }
     * @apiErrorExample  错误返回
     * {
     *   "msg": "获取自己的购物车信息失败"
     * }
     */

  async index() {
    const { ctx } = this;
    try {
      const { ShoppingCart, Goods, GoodsPhoto } = this.app.model.Tables.Shop;
      const { Admin } = this.app.model.Tables.Com;
      const query = this.ctx.query;
      const where = {
        // 根据用户id去购物车匹配
        user_id: this.ctx.userInfo.id,
      };
      where.project_id =
        ctx.userInfo.project_id ||
        (this.ctx.adminInfo && this.ctx.adminInfo.project_id);
      const result = await ShoppingCart.findAndCountAll({
        offset: parseInt(query.offset) || 0,
        limit: parseInt(query.limit) || 10,
        order: [['created_at', 'DESC']],
        where,
        include: [
          {
            // 需要的字段
            // attributes: [ 'id', 'path' ],
            // 链接的表
            model: Goods,
            include: [
              {
                // 需要的字段
                attributes: ['id', 'path'],
                // 链接的表
                model: GoodsPhoto,
              },
              {
                // 链接的表
                model: Admin,
                attributes: ['id', 'name'],
              },
            ],
          },
        ],
      });
      if (result) {
        // 更改格式返回
        ctx.body = ctx.response.success(result, '获取成功');
      } else {
        ctx.body = ctx.response.error('获取自己的购物车信息失败');
      }
    } catch (error) {
      ctx.body = ctx.response.error(error.message);
    }
  }

  // 更新购物车
  /**
     * @api {put} /api/shoppingCart/:id 更新购物车单条信息
     * @apiGroup 购物车
     * @apiParam {INTEGER}  num   //商品数量
     * @apiParamExample 参数模板
     {
      "num"": 2,

      }
     * @apiSuccessExample  成功返回
     {
     }
     * @apiErrorExample  错误返回
     * {
     *   "msg": "找不到该购物车单条信息"
     * }
     */

  async update() {
    const { ctx } = this;
    const dataObj = ctx.request.body;
    // console.log('dataObj===', dataObj);
    if (new ctx.helper.checkData(this).checkDataRes) {
      const id = ctx.params.id;
      try {
        const { ShoppingCart } = this.app.model.Tables.Shop;

        const resultUser = await ShoppingCart.findByPk(id);
        if (resultUser && resultUser.dataValues) {
          const result = await resultUser.update(dataObj);
          ctx.body = ctx.response.success(result.dataValues);
        } else {
          ctx.body = ctx.response.error('找不到该购物车信息');
        }
      } catch (error) {
        ctx.body = ctx.response.error(error.message);
      }
    }
  }

  /**
     * @api {delete} /api/shoppingCart/:id 删除购物车一条信息
     * @apiGroup 购物车
     * @apiParamExample 参数模板
     {}
     * @apiSuccessExample 成功返回
     * {
     *    "msg":'删除成功'
     * }
     *
     * @apiErrorExample 错误返回
     * {
     *  "msg":"删除失败"
     * }
     *
     */

  async destroy(toid) {
    const { ctx, service } = this;
    const id = ctx.params.id || toid;
    ctx.body = await service.shop.shoppingCart.destroy(id);
  }
}

module.exports = ShoppingCartController;
